<script setup>
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
import { getOptions } from '@/utils/index.js'
import SltFromApi from '@/components/SltFromApi/SltFromApi.vue'
import RkEditAndAdd from './RkEditAndAdd.vue'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
let name = ''

// 弹窗标题
const title = computed(() => (props.curRow.id ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  orderNo: '',
  productName: '',
  specs: '',
  unit: '',
  commitQuantity: '',
  commitUnitPrice: '',
  commitTotalPrice: '',
  commitSupplier: '',
  desireQuantity: '',
  desireUnitPrice: '',
  desireTotalPrice: '',
  desireSupplier: '',
  realityQuantity: '',
  realityUnitPrice: '',
  realityTotalPrice: '',
  realitySupplier: '',
  arrivalTime: '',
  applyId: '',
  applyName: '',
  notes: '',
  status: '',
  opinion: '',
  spjg: 2
})
// 是否显示弹窗
const show = ref(false)
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    let resObj = {}
    if (props.curRow.id && show.value) {
      const { resultObject } = await api.getCgddInfo({ id: props.curRow.id })
      resObj = resultObject
      name = ''
    } else {
      formData.value = {
        orderNo: '',
        productName: '',
        specs: '',
        unit: '',
        commitQuantity: '',
        commitUnitPrice: '',
        commitTotalPrice: '',
        commitSupplier: '',
        desireQuantity: '',
        desireUnitPrice: '',
        desireTotalPrice: '',
        desireSupplier: '',
        realityQuantity: '',
        realityUnitPrice: '',
        realityTotalPrice: '',
        realitySupplier: '',
        actualQuantity: '',
        arrivalTime: '',
        applyId: '',
        applyName: '',
        notes: '',
        status: '',
        opinion: '',
        spjg: 2
      }
      name = ''
    }
    formData.value = { ...formData.value, ...val, ...resObj }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      orderNo: '',
      productName: '',
      specs: '',
      unit: '',
      commitQuantity: '',
      commitUnitPrice: '',
      commitTotalPrice: '',
      commitSupplier: '',
      desireQuantity: '',
      desireUnitPrice: '',
      desireTotalPrice: '',
      desireSupplier: '',
      realityQuantity: '',
      realityUnitPrice: '',
      realityTotalPrice: '',
      realitySupplier: '',
      actualQuantity: '',
      arrivalTime: '',
      applyId: '',
      applyName: '',
      notes: '',
      status: '',
      opinion: '',
      spjg: 2
    }
    name = ''
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    // 如果是待审核，有两种可能，如果不是就加一
    let status = Number(formData.value.status) + 1
    if (formData.value.status + '' === '1') {
      status = formData.value.spjg
    }
    let params = {
      ...formData.value,
      ...info,
      status
    }
    await api.editCgdd(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info
    }
    params.productName = name
    await api.addCgdd(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
const getRows = (val, index) => {
  let test = val
  if (index) {
    name = index
  }
  if (test.length > 0) {
    test = val.filter((item) => item.value === index)
    if (test.length > 0) {
      name = test[0].label
    } else {
      name = index
    }
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const rkRef = ref()
const submit = async () => {
  if (formData.value.status + '' === '4') {
    submitLoading.value = true
    rkRef.value
      .submit()
      .then(async () => {
        await emitItem({})
        show.value = false
        emits('init')
        setTimeout(() => {
          submitLoading.value = false
        }, 30)
      })
      .catch((e) => {
        console.log(e)
        setTimeout(() => {
          submitLoading.value = false
        }, 30)
      })
  } else {
    formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
  }
}
defineExpose({ open })

const stepItems = computed(() => {
  if (formData.value.status + '' === '0') {
    return [{ title: '待审核' }, { title: '已拒绝' }]
  } else {
    return [
      { title: '待审核' },
      { title: '已通过' },
      { title: '采购中' },
      { title: '已到货' },
      { title: '已入库' }
    ]
  }
})

const rkForm = computed(() => {
  return {
    ...props.curRow,
    outTypeId: 1,
    price: formData.value.realityUnitPrice,
    quantity: formData.value.actualQuantity
  }
})
//cs
const test = (val) => {
  console.log(val)
}
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    width="700px"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <template v-if="formData.status === ''">
        <a-form-item
          label="物资名称"
          name="productName"
          :rules="[{ required: true, message: '请输入' }]"
          @change="test"
        >
          <SltFromApi
            v-model="formData.productName"
            :params="{
              outBigTypeId: formData.outBigTypeId,
              outSmallTypeId: formData.outSmallTypeId
            }"
            :getRows="getRows"
          />
        </a-form-item>
        <a-form-item
          label="采购数量"
          name="desireQuantity"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number
            :min="0"
            v-model:value="formData.desireQuantity"
            allowClear
            @change="formData.desireTotalPrice = formData.desireQuantity * formData.desireUnitPrice"
          />
        </a-form-item>
        <a-form-item label="规格" name="specs" :rules="[{ required: true, message: '请输入' }]">
          <a-input v-model:value="formData.specs" allowClear />
        </a-form-item>
        <a-form-item label="单位" name="unit" :rules="[{ required: true, message: '选择' }]">
          <a-select
            v-model:value="formData.unit"
            allowClear
            :options="getOptions('unit')"
            :fieldNames="{ label: 'constLabel', value: 'constLabel' }"
          />
        </a-form-item>
        <a-form-item
          label="预计单价(元)"
          name="desireUnitPrice"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number
            :min="0"
            v-model:value="formData.desireUnitPrice"
            allowClear
            @change="formData.desireTotalPrice = formData.desireQuantity * formData.desireUnitPrice"
          />
        </a-form-item>
        <a-form-item
          label="预计总价(元)"
          name="desireTotalPrice"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number :min="0" v-model:value="formData.desireTotalPrice" allowClear disabled />
        </a-form-item>
        <a-form-item label="期望供货商" name="desireSupplier">
          <a-input v-model:value="formData.desireSupplier" allowClear />
        </a-form-item>
        <a-form-item label="备注" name="notes">
          <a-input v-model:value="formData.notes" allowClear />
        </a-form-item>
      </template>
      <template v-else>
        <a-steps
          :current="Number(formData.status) - 1"
          size="small"
          :items="stepItems"
          style="margin-bottom: 20px"
        />
      </template>
      <template v-if="formData.status + '' === '1'">
        <a-form-item label="审批结果" name="spjg" :rules="[{ required: true, message: '请选择' }]">
          <a-select
            v-model:value="formData.spjg"
            allowClear
            :options="[
              { label: '通过', value: 2 },
              { label: '拒绝', value: 0 }
            ]"
          />
        </a-form-item>
        <a-form-item label="审批意见" name="opinion">
          <a-textarea v-model:value="formData.opinion" allowClear />
        </a-form-item>
      </template>
      <template v-if="formData.status + '' === '2'">
        <a-form-item
          label="采购数量"
          name="realityQuantity"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number
            :min="0"
            v-model:value="formData.realityQuantity"
            allowClear
            @change="
              formData.realityTotalPrice = formData.realityQuantity * formData.realityUnitPrice
            "
          />
        </a-form-item>
        <a-form-item
          label="采购单价(元)"
          name="realityUnitPrice"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number
            :min="0"
            v-model:value="formData.realityUnitPrice"
            allowClear
            @change="
              formData.realityTotalPrice = formData.realityQuantity * formData.realityUnitPrice
            "
          />
        </a-form-item>
        <a-form-item
          label="采购总价(元)"
          name="realityTotalPrice"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number :min="0" v-model:value="formData.realityTotalPrice" allowClear disabled />
        </a-form-item>
        <a-form-item
          label="供货商"
          name="realitySupplier"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input v-model:value="formData.realitySupplier" allowClear />
        </a-form-item>
      </template>
      <template v-if="formData.status + '' === '3'">
        <a-form-item
          label="到货数量"
          name="actualQuantity"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number :min="0" v-model:value="formData.actualQuantity" allowClear />
        </a-form-item>
        <a-form-item
          label="到货时间"
          name="arrivalTime"
          :rules="[{ required: true, message: '请选择' }]"
        >
          <a-date-picker
            v-model:value="formData.arrivalTime"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
          />
        </a-form-item>
      </template>
      <template v-if="formData.status + '' === '4'">
        <RkEditAndAdd ref="rkRef" :curRow="rkForm" />
      </template>
      <template v-if="formData.status + '' === '5'">
        <div>已入库</div>
      </template>
      <template v-if="formData.status + '' === '6'">
        <div>已入库</div>
      </template>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>